#include "searchdialog.h"
#include <QFileInfo>
#include <QInputDialog>
#include <QRegularExpression>
#include <QListWidgetItem>
#include <QDebug>

SearchDialog::SearchDialog(const QStringList& paths, QWidget* parent)
    : QDialog(parent), romPaths(paths)
{
    setWindowTitle("搜索 ROM");
    resize(500, 400);

    listWidget = new QListWidget(this);
    listWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addWidget(listWidget);

    connect(listWidget, &QListWidget::itemClicked, this, &SearchDialog::handleItemClicked);

    // 弹出输入框获取关键词
    bool ok = false;
    QString keyword = QInputDialog::getText(this, "搜索", "请输入关键词：", QLineEdit::Normal, "", &ok).trimmed();
    if (ok && !keyword.isEmpty()) {
        populateList(keyword);
    } else {
        close(); // 取消搜索则关闭窗口
    }
}

QString SearchDialog::cleanName(const QString& text) {
    static const QRegularExpression specialCharsRegex("[\\d\\.\\s\\(\\)]");
    static const QRegularExpression bracketsRegex("\\[.*\\]|\\(.*\\)");
    QString cleaned = text;
    cleaned.remove(specialCharsRegex);
    cleaned.remove(bracketsRegex);
    return cleaned;
}

void SearchDialog::populateList(const QString& keyword) {
    QString cleanedKeyword = cleanName(keyword);

    for (const QString& path : romPaths) {
        QFileInfo info(path);
        QString fileName = info.fileName();
        QString baseName = info.baseName();

        QString cleanedBase = cleanName(baseName);

        if (fileName.contains(keyword, Qt::CaseInsensitive) ||
            cleanedBase.contains(cleanedKeyword, Qt::CaseInsensitive)) {

            QString displayText = fileName;
            // 高亮匹配部分（HTML 显示）
            displayText.replace(QRegularExpression(QRegularExpression::escape(keyword), QRegularExpression::CaseInsensitiveOption),
                                QString("<span style='color:red;font-weight:bold;'>%1</span>").arg(keyword));

            QListWidgetItem* item = new QListWidgetItem();
            item->setData(Qt::UserRole, path);     // 原始路径
            item->setText(fileName);               // 保留纯文本，避免 HTML
            item->setToolTip(path);                // 悬停显示完整路径
            item->setWhatsThis(displayText);       // 自定义显示用
            listWidget->addItem(item);
        }
    }

    // 自定义高亮显示：用 delegate 或直接 on paint 可以扩展支持 HTML 富文本
    for (int i = 0; i < listWidget->count(); ++i) {
        QListWidgetItem* item = listWidget->item(i);
        item->setText(item->whatsThis());  // 显示带高亮的文本
    }
}

void SearchDialog::handleItemClicked(QListWidgetItem* item) {
    QString romPath = item->data(Qt::UserRole).toString();
    emit romSelected(romPath);
    accept(); // 关闭对话框
}
